package com.projects.modular.api.controller;

import java.io.*;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.UUID;
import java.util.regex.Pattern;

import com.projects.modular.system.model.WeChatMiniProgramSession;
import com.projects.modular.system.task.SseScheduledTask;
import com.projects.modular.system.utils.SendSmsVerifyCode;
import com.projects.modular.system.utils.WeChatMiniProgramUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.projects.config.web.ResponseData;
import com.projects.config.web.WebProperties;
import com.projects.core.common.exception.BizExceptionEnum;
import com.projects.modular.realty.entity.RegisteredUsers;
import com.projects.modular.realty.model.params.RegisteredUsersParam;
import com.projects.modular.realty.service.RegisteredUsersService;
import com.projects.modular.system.model.Login;
import com.projects.modular.system.service.UserService;

import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;

import javax.servlet.http.HttpServletResponse;


/**
 * 接口控制器提供
 */
@RestController
@Validated
@RequestMapping("/api")
public class ApiController extends BaseController {
    final static int NEIGHBORHOOD_NUM = 10;
    final static int RECOMMENDER_NUM = 5;
    @Autowired
    private UserService userService;
    @Autowired
    private WebProperties webProperties;

    @Autowired
    private RegisteredUsersService registeredUsersService;

    // 手机号验证正则表达式
    private static final Pattern PHONE_PATTERN = Pattern.compile("^1[3-9]\\d{9}$");


    /**
     * 注册
     *
     * @param registeredUsersParam
     * @return
     */
    @PostMapping(value = "/registerUser")
    public ResponseData registerUser(@RequestBody RegisteredUsersParam registeredUsersParam) {

        try {
            // 验证用户名(手机号)格式
            String userName = registeredUsersParam.getUserName();
            if (userName == null || !PHONE_PATTERN.matcher(userName).matches()) {
                return ResponseData.error("用户名必须是有效的手机号");
            }

            QueryWrapper<RegisteredUsers> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_name", registeredUsersParam.getUserName());
            RegisteredUsers registerUser = registeredUsersService.getOne(queryWrapper);
            if (null != registerUser) {
                return ResponseData.error("用户已注册");
            }

            // 密码强度校验：必须包含数字和字母，长度至少6位
            String password = registeredUsersParam.getPassWord();
            if (password == null || password.length() < 6) {
                return ResponseData.error("密码长度不能少于6位");
            }

            boolean hasDigit = false;
            boolean hasLetter = false;
            for (char c : password.toCharArray()) {
                if (Character.isDigit(c)) {
                    hasDigit = true;
                } else if (Character.isLetter(c)) {
                    hasLetter = true;
                }
            }

            if (!hasDigit || !hasLetter) {
                return ResponseData.error("密码必须同时包含数字和字母");
            }

            registeredUsersService.add(registeredUsersParam);

            return ResponseData.success();
        } catch (Exception e) {
            return ResponseData.error(e.getMessage());
        }

    }


    /**
     * 微信登录
     *
     * @param code
     * @return
     */
    @ApiOperation("")
    @GetMapping(value = "/subscribeMessage")
    public ResponseData subscribeMessage(@RequestParam String code, @RequestParam String userName) {
        // 调用微信登录接口 获取用户openid
        WeChatMiniProgramSession weChatMiniProgramSession = WeChatMiniProgramUtil.code2Session("wx39d95a2c0218c00f", "66eae34feaaf87c0e7faa13c0cb7f87c", code);
        if (weChatMiniProgramSession != null) {
            String openid = weChatMiniProgramSession.getOpenid();
            // 更新用户订阅状态
            registeredUsersService.updateSubscribeStatus(1, userName, openid);
            return ResponseData.success(openid);
        }
        return ResponseData.error("登录失败");
    }


    /**
     * 订阅消息推送
     */
    @ApiOperation("订阅消息推送")
    @GetMapping(value = "/subscribe")
    public ResponseData subscribe(@RequestParam String openId) {
        return ResponseData.success(SseScheduledTask.sendMessage(openId));
    }


    /**
     * 获取登录验证码
     */
    @GetMapping(value = "/getLoginVerifyCode")
    public ResponseData getLoginVerifyCode(@RequestParam String phone) {
        try {
            boolean res = SendSmsVerifyCode.sendLoginSms(phone);
            if (!res) {
                return ResponseData.error("发送验证码失败");
            }
        } catch (Exception e) {
            return ResponseData.error("发送验证码失败");
        }
        return ResponseData.success("发送验证码成功");
    }


    /**
     * 登录
     *
     * @param registerUserParam
     * @return
     */
    @PostMapping(value = "/loginUser")
    public ResponseData loginUser(@RequestBody RegisteredUsersParam registerUserParam) {

        try {
            // 验证用户名(手机号)格式
            String userName = registerUserParam.getUserName();
            if (userName == null || !PHONE_PATTERN.matcher(userName).matches()) {
                return ResponseData.error("用户名必须是有效的手机号");
            }

            QueryWrapper<RegisteredUsers> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_name", registerUserParam.getUserName());
            RegisteredUsers registerUser = registeredUsersService.getOne(queryWrapper);
            if (null == registerUser) {
                return ResponseData.error("用户不存在");
            }

            if (!registerUser.getPassWord().equals(registerUserParam.getPassWord())) {
                return ResponseData.error("密码错误");
            }

            Login login = new Login();
            login.setUserName(registerUser.getUserName());
            login.setId(registerUser.getUserId());
            login.setHeadIcon(registerUser.getPic());
            return ResponseData.success(login);
        } catch (Exception e) {
            return ResponseData.error(e.getMessage());
        }

    }


    /**
     * 修改用户资料
     *
     * @param registeredUsersParam
     * @return
     */
    @PostMapping(value = "/editUser")
    public ResponseData editUser(@RequestBody RegisteredUsersParam registeredUsersParam) {

        try {
            registeredUsersService.update(registeredUsersParam);

            return ResponseData.success();
        } catch (Exception e) {
            return ResponseData.error(e.getMessage());
        }

    }


    /**
     * 上传头像
     *
     * @param uploadfile
     * @return
     */
    @RequestMapping(value = "/upload")
    @ResponseBody
    public ResponseData imgUpload(@RequestParam(value = "uploadfile", required = false) MultipartFile[] uploadfile) {
        List<String> pics = new ArrayList<>();
        for (MultipartFile file : uploadfile) {
            String fileSavePath = "";
            String serverSavePath = "";
            String pictureName = UUID.randomUUID().toString() + "." + ToolUtil.getFileSuffix(file.getOriginalFilename());
            try {
                fileSavePath = webProperties.getFileUploadPath();
                serverSavePath = webProperties.getServerUploadPath();
                file.transferTo(new File(fileSavePath + pictureName));
            } catch (Exception e) {
                throw new ServiceException(BizExceptionEnum.UPLOAD_ERROR);
            }
            pics.add(serverSavePath + pictureName);
        }

        return ResponseData.success(200, "上传成功", pics.get(0));
    }


    /**
     * 获取用户账号资料详情
     *
     * @param userId
     * @return
     */
    @PostMapping(value = "/getinfo")
    public ResponseData getinfo(Long userId) {

        try {

            RegisteredUsers registeredUsers = registeredUsersService.getById(userId);

            return ResponseData.success(registeredUsers);
        } catch (Exception e) {
            return ResponseData.error(e.getMessage());
        }
    }


    @ApiOperation("下载字体文件")
    @GetMapping("/downloadFont")
    public ResponseData downloadFont() {
        try {
            // 获取字体文件
            ClassPathResource fontResource = new ClassPathResource("fonts/AlimamaShuHeiTi-Bold.ttf");

            // 读取文件内容到字节数组 (使用较小的缓冲区以减少内存压力)
            byte[] fileContent;
            try (InputStream is = fontResource.getInputStream();
                 ByteArrayOutputStream buffer = new ByteArrayOutputStream()) {
                int nRead;
                // 使用较小的缓冲区以减少内存压力
                byte[] data = new byte[4096];
                while ((nRead = is.read(data, 0, data.length)) != -1) {
                    buffer.write(data, 0, nRead);
                }
                buffer.flush();
                fileContent = buffer.toByteArray();
            }

            // 将字节数组转换为Base64编码
            String base64Encoded = Base64.getEncoder().encodeToString(fileContent);

            // 返回Base64编码的数据
            return ResponseData.success(base64Encoded);
        } catch (IOException e) {
            System.err.println("字体文件读取异常: " + e.getMessage());
            e.printStackTrace();
            return ResponseData.error("字体文件读取失败");
        } catch (Exception e) {
            System.err.println("字体文件处理异常: " + e.getMessage());
            e.printStackTrace();
            return ResponseData.error("服务器内部错误");
        }
    }

}